﻿using AutoMapper.Internal.Mappers;
using Minio.DataModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Himp.Platform
{
    public class MenuService : CrudAppService<Menu, MenuDto, Guid, MenuInput, MenuCreateDto, MenuUpdateDto>
    {
        private IRepository<Menu, Guid> _menuRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MenuRepository"></param>
        public MenuService(IRepository<Menu, Guid> MenuRepository) : base(MenuRepository)
        {
            _menuRepository = MenuRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<MenuDto>> GetListAsync(MenuInput input)
        {
            var iQuery = await _menuRepository.GetQueryableAsync();
            var allMenus = ObjectMapper.Map<List<Menu>, List<MenuDto>>(iQuery.ToList());
            var rootMenu = allMenus.Where(m => m.ParentId == null);
            List<MenuDto> itemsDto = new List<MenuDto>();

            foreach (var menu in rootMenu)
            {
                menu.Children = new List<MenuDto>();
                SetChildren(allMenus, menu);
                itemsDto.Add(menu);
            }

            return new PagedResultDto<MenuDto>(itemsDto.Count, itemsDto);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override Task<MenuDto> CreateAsync(MenuCreateDto input)
        {
            return base.CreateAsync(input);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="allMenus"></param>
        /// <param name="menuConvert"></param>
        private void SetChildren(List<MenuDto> allMenus, MenuDto menuConvert)
        {
            var childrenMenus = allMenus.Where(m => m.ParentId == menuConvert.Id);

            foreach (var menu in childrenMenus)
            {
                menuConvert.Children.Add(menu);
                SetChildren(allMenus, menu);
            }

        }
    }
}
